package com.ls.bjtool.filter;

import com.alibaba.fastjson.JSONObject;
import com.ls.bjtool.bean.RequestBean;
import com.ls.bjtool.utils.HttpUtil;
import org.apache.commons.lang.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@WebFilter(filterName = "requestWrapperFilter", urlPatterns = "/*")
public class ChannelFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        ChannelWrapper requestWrapper = new ChannelWrapper((HttpServletRequest) request);
        RequestBean requestBean = new RequestBean();
        requestBean.setUri(requestWrapper.getRequestURI());
        requestBean.setMethod(requestWrapper.getMethod().toUpperCase());
        requestBean.setIp(HttpUtil.getIPAddress(requestWrapper));
        Enumeration<String> headerNames = requestWrapper.getHeaderNames();
        Map<String, String> headeds = new HashMap<>();
        while (headerNames.hasMoreElements()) {
            String headerName = (String) headerNames.nextElement();
            String headerValue = requestWrapper.getHeader(headerName);
            headeds.put(headerName, headerValue);
        }
        requestBean.setHeadeds(headeds);
        //ChannelWrapper jsonParam = new ChannelWrapper(request);
        String jsonParamBody = requestWrapper.getBody();
        if (StringUtils.isNotBlank(jsonParamBody)) {
            Map<String, String> bodyParameters = JSONObject.parseObject(jsonParamBody, HashMap.class);
            requestBean.setBodyParameters(bodyParameters);
        }
        String queryString = requestWrapper.getQueryString();
        if (StringUtils.isNotBlank(queryString)) {
            requestBean.setQueryString(queryString);
        }
        HttpUtil.setRequestInfo(requestBean);
        chain.doFilter(requestWrapper, response);
    }

    @Override
    public void destroy() {
        HttpUtil.removeRequestInfo();
    }

}